<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\FleaWallet;
use App\Models\FleaWithdrawal;
use Illuminate\Http\Request;

class FleaWithdrawalController extends Controller
{
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;

        $user_id = $request->get('user_id');

        $state = $request->get('state', 1);
        $where[] = ['state', '=', $state];

        if ($user_id) {
            $where[] = ['user_id', '=', $user_id];
        }

        $data = FleaWithdrawal::query()->select('id', 'user_id', 'money', 'state', 'created_at', 'examine_at', 'mark')->where($where)->offset($offset)->limit($limit)->get()->append('state_text');

        $response['data'] = $data;
        $response['count'] = FleaWithdrawal::query()->where($where)->count();
        $response['pages'] = ceil($response['count'] / $limit);

        return $this->success($response);
    }

    public function store(Request $request)
    {
        $state = $request->post('state');
        $id = $request->post('id');
        $mark = $request->post('mark');

        try {
            FleaWithdrawal::examine($id, $state, $mark);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
        return $this->success();
    }

    /**
     * @param Request $request
     * @return array
     * 用户累计支出/收入列表
     */
    public function recordList(Request $request)
    {
        try {
            $type = $request->get('type', 1);
            $where[] = ['type', '=', $type];

            $time = $request->get('time', date('Y-m'));

            $page = $request->get('page', 1);
            $limit = $request->get('limit', 20);

            $user_id = $request->get('user_id');

            $data = FleaWallet::adminRecordList($user_id, $where, $time, $page, $limit);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
        return $this->success($data);
    }
}
